import { memo, useEffect, useMemo, useRef, useState } from "react";
import { OrderType } from "../../../../types/order";
import { Card } from "antd";
import dayjs from "dayjs";
import { month_map } from "../../../../constant";
import * as echarts from "echarts";

const StudentSittuation = memo(({ orders }: { orders: OrderType[] }) => {
  const chartRef = useRef(null);
  const chatXAxisData: string[] = [];
  for (let i = 0; i <= dayjs().month(); i++) {
    chatXAxisData.push(month_map.get(i + 1) ?? "");
  }
  const [formatOrders, setFormatOrders] = useState<Map<string, number>>(new Map());
  useEffect(() => {
    if (orders && orders.length > 0) {
      const currentOrders: typeof formatOrders = new Map();
      for (const order of orders) {
        if (!currentOrders.has(order.userId)) {
          currentOrders.set(order.userId, Number(order.buyTime));
        }
      }
      setFormatOrders(currentOrders);
    }
  }, [orders]);

  const aggregatedData = useMemo(() => {
    const copyFormatOrders = Array.from(formatOrders.values());
    // 用于剔除已经遍历过的数据;
    let ergodicEndNum = 0;
    const data: number[] = new Array(dayjs().month() + 1).fill(0) as number[];
    for (let i = 0; i <= dayjs().month(); i++) {
      // 递加上一个月的数量
      data[i] = i - 1 >= 0 ? data[i - 1] : 0;
      // 每一个月截止的时间戳
      const monthEnd = dayjs(`${dayjs().year()}-${i + 1 > 9 ? i + 1 : "0" + String(i + 2)}-01`);
      for (let j = ergodicEndNum; j < copyFormatOrders.length; j++) {
        if (dayjs(copyFormatOrders[j]).isBefore(monthEnd)) {
          data[i]++;
          ergodicEndNum++;
        } else {
          break;
        }
      }
    }
    return data;
  }, [formatOrders]);

  useEffect(() => {
    const option = {
      graphic: {
        type: "text",
        left: "center",
        top: "middle",
        style: {
          text: orders.length === 0 ? "暂无学员" : "",
          fontSize: 20,
          fontWeight: "bold",
          fill: "#aaa"
        }
      },
      legend: {
        data: [
          "学员总数"
        ]
      },
      xAxis: {
        type: "category",
        data: chatXAxisData
      },
      yAxis: [
        {
          type: "value",
          name: "位",
          nameTextStyle: {
            color: "#838383"
          },
          min: 0,
          interval: 1,
          minInterval: 1
        }
      ],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow"
        },
        textStyle: {
          color: "#fff",
          align: "left",
          fontSize: 14
        },
        backgroundColor: "rgba(0,0,0,0.8)"
      },
      series: [
        {
          name: "学员总数",
          data: aggregatedData,
          yAxisIndex: 0,
          type: "line",
          smooth: true,
          itemStyle: {
            color: "#9c5bff"
          }
        }
      ]
    };
    const chartInstance = echarts.init(chartRef.current);
    chartInstance.setOption(option);
  }, [aggregatedData]);


  return (
    <Card title="学员总数" bordered={false} style={{ width: "100%" }}>
      <div ref={chartRef} style={{ width: "100%", height: "30vh" }}></div>
    </Card>
  );
});

export default StudentSittuation;
